<template>
	<uni-popup ref="popupRef" type="bottom">
		<scroll-view scroll-y class="scroll_box">
			<view class="popup-container">
				<!-- 头部标题 -->
				<view class="header">
					<text class="title">{{ props.serviceInfo?.goods?.name }} | ¥{{ props.serviceInfo?.goodsSkuList?.[0]?.price }}/次</text>
					<view class="close-icon" @tap="handleCancel">×</view>
				</view>
				<!-- 宠物选择区域 -->
				<view class="section" v-if="serviceInfo?.goods?.pickServicePet">
					<view class="section-title">预约服务宠物</view>
					<view class="pet-list">
						<view v-for="pet in petList" :key="pet.id" :class="['pet-item', { active: currentScheme.showPet(pet) }]" @tap="togglePet(pet)">
							{{ pet.petNickName }}
						</view>
					</view>
				</view>
				<!-- 日期选择区域 -->
				<view class="section" v-if="serviceInfo?.goods?.pickServiceDate">
					<view class="section-title">预约服务日期</view>
					<view class="date-list">
						<view v-for="date in dateList" :key="date" :class="['date-item', { active: currentScheme.showDate(date) }]" @tap="toggleDate(date)">
							{{ date }}
						</view>
					</view>
				</view>
				<!-- 预约结果展示 -->
				<view class="section">
					<view class="section-title">预约结果</view>
					<view class="result-list">
						<view v-for="(item, index) in combinedResults" :key="index" class="result-item">
							<view class="pet-name">
								<text v-if="serviceInfo?.goods?.pickServicePet == 1">{{ item.petNickName }}</text>
								<text v-else-if="serviceInfo?.goods?.pickServiceDate == 1 && serviceInfo?.goods?.pickServicePet == 0">{{ item.date }}</text>
							</view>
							<view class="date" v-if="serviceInfo?.goods?.pickServiceDate == 1 && serviceInfo?.goods?.pickServicePet == 1">{{ item.date }}</view>
							<view class="delete-icon" @tap="deleteResult(index)">×</view>
						</view>
					</view>
				</view>
				<!-- 底部按钮 -->
				<view class="footer">
					<view class="btn cancel" @tap="handleCancel">取消</view>
					<view class="btn confirm" @tap="handleConfirm">确认选择</view>
				</view>
			</view>
		</scroll-view>
	</uni-popup>
</template>

<script setup>
import { ref, withDefaults, computed, watch, onMounted, nextTick } from 'vue';

const emit = defineEmits(['cancel', 'confirm']);

const props = defineProps({
	serviceInfo: {
		type: Object,
		default: {}
	},
	petList: {
		type: Array,
		default: []
	},
	dateList: {
		type: Array,
		default: []
	}
});

const popupRef = ref();

const combinedResults = ref([
	// { petId: '', petNickName: '', date: '' }
]);

// 选中的宠物列表（包含日期）
const selectedPetsListWithDates = ref([
	// {
	// 	petId: '',
	// 	petNickName: '',
	// 	dates: ['xxxx-xx-xx']
	// }
]);

// 选中的宠物或时间列表（单独）
const selectPetOrDateList = ref([
	// {
	// 	petId: '',
	// 	petNickName: '',
	// 	date: ''
	// }
]);

const currentPetInfoWithDates = ref({});

const schemeInfo = {
	integrated: {
		init: integratedInit,
		showDate: integratedShowSelectedDates,
		showPet: integratedShowPet,
		selectPet: integratedSelectPet,
		selectDate: integratedSelectDate,
		updateList: integratedUpdateList,
		updateResult: integratedUpdateResult
	},
	single: {
		init: singleInit,
		showDate: singleShowSelectedDates,
		showPet: singleShowPet,
		selectPet: singleSelectPet,
		selectDate: singleSelectDate,
		updateList: singleUpdateList,
		updateResult: singleUpdateResult
	}
};

const currentScheme = computed(() => {
	if (!props.serviceInfo || !props.serviceInfo.goods) return {};
	const pickServiceDate = props.serviceInfo?.goods?.pickServiceDate;
	const pickServicePet = props.serviceInfo?.goods?.pickServicePet;
	return pickServiceDate == 1 && pickServicePet == 1 ? schemeInfo.integrated : schemeInfo.single;
});

const open = (data) => {
	const hasPopupRef = popupRef.value && popupRef.value.open;
	const hasServiceInfo = props.serviceInfo && props.serviceInfo.goods;
	if (!hasPopupRef || !hasServiceInfo) {
		setTimeout(() => {
			open(data);
		}, 500);
		return;
	}
	init(data);
};

const init = (data) => {
	currentScheme.value.init(data);
};

// 切换宠物选择
const togglePet = (pet) => {
	currentScheme.value.selectPet(pet);
};

// 切换日期选择
const toggleDate = (date) => {
	currentScheme.value.selectDate(date);
};

// 更新组合结果的方法
const updateCombinedResults = () => {
	currentScheme.value.updateResult();
};

// 删除结果项
const deleteResult = (index) => {
	// 1. 直接从组合结果中删除当前项
	// const deletedArr = combinedResults.value.splice(index, 1);
	// const deletedInfo = deletedArr[0] || {}
	combinedResults.value.splice(index, 1);
	updateSelectedPetsAndDates();
};

// 更新选中的宠物和日期
const updateSelectedPetsAndDates = () => {
	currentScheme.value.updateList();
};

function integratedInit(data) {
	selectedPetsListWithDates.value = [];
	props.petList.forEach((pet) => {
		selectedPetsListWithDates.value.push({
			petId: pet.id,
			petNickName: pet.petNickName,
			dates: []
		});
	});
	combinedResults.value = [...data];
	updateSelectedPetsAndDates();
	selectDefaultPet();
	popupRef.value.open();
}

function integratedShowSelectedDates(date) {
	return currentPetInfoWithDates.value?.dates?.some((selectedDate) => selectedDate == date);
}
function integratedShowPet(pet) {
	return currentPetInfoWithDates.value.petId == pet.id;
}

function integratedSelectPet(pet) {
	currentPetInfoWithDates.value = selectedPetsListWithDates.value.find((petInfo) => petInfo.petId == pet.id);
}

function integratedSelectDate(date) {
	const index = currentPetInfoWithDates.value?.dates?.findIndex((selectedDate) => selectedDate == date);
	if (index == -1) {
		currentPetInfoWithDates.value.dates.push(date);
		currentPetInfoWithDates.value.dates.sort((a, b) => new Date(a).getTime() - new Date(b).getTime());
	} else {
		currentPetInfoWithDates.value.dates.splice(index, 1);
	}

	updateCombinedResults();
}

function integratedUpdateList() {
	selectedPetsListWithDates.value.forEach((petInfo) => (petInfo.dates = []));
	combinedResults.value.forEach((result) => {
		const info = selectedPetsListWithDates.value.find((petInfo) => petInfo.petId == result.petId);
		if (info) {
			const dates = info.dates || [];
			const isExisted = dates.some((date) => date == result.date);
			if (isExisted) return;
			dates.push(result.date);
		} else {
			selectedPetsListWithDates.value.push({
				petId: result.petId,
				petNickName: result.petNickName,
				dates: [result.date]
			});
		}
	});
}

function integratedUpdateResult() {
	combinedResults.value = [];

	selectedPetsListWithDates.value.forEach((item) => {
		item.dates.forEach((date) => {
			combinedResults.value.push({ petId: item.petId, petNickName: item.petNickName, date });
		});
	});
}

const selectDefaultPet = () => {
	if (selectedPetsListWithDates.value.length > 0) {
		const id = props.petList?.[0]?.id;
		currentPetInfoWithDates.value = selectedPetsListWithDates.value.find((petInfo) => petInfo.petId == id);
	}
};

// 单独选择宠物或日期的方法————开始
function singleInit(data) {
	selectPetOrDateList.value = [];
	combinedResults.value = [...data];
	updateSelectedPetsAndDates();
	popupRef.value.open();
}

function singleShowSelectedDates(date) {
	return selectPetOrDateList.value.some((selectedInfo) => selectedInfo.date == date);
}
function singleShowPet(pet) {
	return selectPetOrDateList.value.some((selectedInfo) => selectedInfo.petId == pet.id);
}
function singleSelectPet(pet) {
	const index = selectPetOrDateList.value.findIndex((selectedInfo) => selectedInfo.petId == pet.id);
	if (index == -1) {
		selectPetOrDateList.value.push({
			petId: pet.id,
			petNickName: pet.petNickName,
			date: undefined
		});
	} else {
		selectPetOrDateList.value.splice(index, 1);
	}
	updateCombinedResults();
}

function singleSelectDate(date) {
	const index = selectPetOrDateList.value.findIndex((selectedInfo) => selectedInfo.date == date);
	if (index == -1) {
		selectPetOrDateList.value.push({
			petId: undefined,
			petNickName: undefined,
			date
		});
		selectPetOrDateList.value.sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime());
	} else {
		selectPetOrDateList.value.splice(index, 1);
	}

	updateCombinedResults();
}

function singleUpdateList() {
	selectPetOrDateList.value = [];
	combinedResults.value.forEach((result) => {
		selectPetOrDateList.value.push({ ...result });
	});
}

function singleUpdateResult() {
	combinedResults.value = [];

	selectPetOrDateList.value.forEach((item) => {
		combinedResults.value.push({ ...item });
	});
}

const handleCancel = () => {
	popupRef.value.close();
	emit('cancel');
};

const handleConfirm = () => {
	if (!validateConfigInfo()) return;

	popupRef.value.close();
	emit('confirm', combinedResults.value);
};

const validateConfigInfo = () => {
	const pickServicePet = props.serviceInfo.goods.pickServicePet;
	const pickServiceDate = props.serviceInfo.goods.pickServiceDate;
	if (combinedResults.value.length === 0) {
		if (pickServicePet == 0 || (pickServicePet == 1 && pickServiceDate == 1)) {
			uni.showToast({
				title: '请选择服务日期',
				icon: 'none'
			});
		} else if (pickServiceDate == 0) {
			uni.showToast({
				title: '请选择服务宠物',
				icon: 'none'
			});
		}
		return false;
	}
	return true;
};

defineExpose({
	open
});
</script>

<style lang="scss" scoped>
.scroll_box {
	height: 85vh;
	box-sizing: border-box;
	background: #fff;
	border-radius: 24rpx 24rpx 0 0;
}
.popup-container {
	padding: 70rpx 32rpx 0;
	padding-bottom: calc(88rpx + constant(safe-area-inset-bottom));
	padding-bottom: calc(88rpx + env(safe-area-inset-bottom));
	box-sizing: border-box;

	.header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 40rpx;
		padding-bottom: 46rpx;
		border-bottom: 1rpx solid #f5f6f7;

		.title {
			font-weight: bold;
			font-size: 36rpx;
			color: #1b2120;
		}

		.close-icon {
			font-size: 40rpx;
			color: #1b2120;
		}
	}

	.section {
		margin-bottom: 32rpx;

		.section-title {
			font-size: 30rpx;
			color: #1a1a1a;
			margin-bottom: 24rpx;
		}

		.pet-list,
		.date-list {
			display: flex;
			flex-wrap: wrap;
			gap: 16rpx;
			padding-bottom: 40rpx;
			border-bottom: 1rpx solid #f5f6f7;

			.pet-item,
			.date-item {
				border: 1rpx solid #cacccc;
				padding: 16rpx;
				background: #ffffff;
				border-radius: 8rpx;
				font-size: 26rpx;
				color: #808080;

				&.active {
					border-color: #ff6084;
					color: #ff6084;
				}
			}
		}

		.result-list {
			min-height: 180rpx;
			display: flex;
			align-items: center;
			flex-wrap: wrap;
			gap: 24rpx 16rpx;
			padding: 24rpx;
			background-color: #f9f6f6;
			border-radius: 24rpx;
			box-sizing: border-box;

			.result-item {
				position: relative;
				background: #fff;
				padding: 24rpx;
				border-radius: 12rpx;
				border: 1rpx solid #e6e6e6;

				.pet-name {
					flex: 1;
					font-weight: bold;
					font-size: 26rpx;
					color: #1a1a1a;
				}

				.date {
					margin-top: 16rpx;
					font-size: 22rpx;
					color: #7c807f;
				}

				.delete-icon {
					color: #ff5252;
					font-size: 32rpx;
					position: absolute;
					right: 0;
					top: 0;
					transform: translate(50%, -50%);
					z-index: 1;
				}
			}
		}
	}

	.footer {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		display: flex;
		gap: 16rpx;
		padding: 0 32rpx;
		padding-top: 8rpx;
		padding-bottom: calc(constant(safe-area-inset-bottom));
		padding-bottom: calc(env(safe-area-inset-bottom));
		border-top: 0.5px solid #e4e6e6;
		background: #fff;
		z-index: 1;

		.btn {
			flex: 1;
			height: 88rpx;
			line-height: 88rpx;
			text-align: center;
			border-radius: 44rpx;
			font-size: 28rpx;
			box-sizing: border-box;

			&.cancel {
				background: #fff;
				border: 2rpx solid #ff6084;
				color: #ff6084;
			}

			&.confirm {
				background: linear-gradient(90deg, #ff6188 0%, #ff5252 100%);
				color: #fff;
			}
		}
	}
}
</style>
